package service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import db.MyHibernateSessionFactory;
import entity.Account;
import service.AccountDAO;

public class AccountDAOImpl implements AccountDAO{

	@Override
	public Account accountLogin(Account ac) {
		Transaction tx = null;
		String hql = "";
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		try {
			tx = session.beginTransaction();
			hql = "from Account where email=? and password=? ";
			Query query = session.createQuery(hql);
			query.setParameter(0, ac.getEmail());
			query.setParameter(1, ac.getPassword());
			List list = query.list();
			tx.commit();
			
			if(list.size() > 0)
			{
				Account tempAc = (Account)(list.get(0));
				return tempAc;
			}
			else{
//					System.out.println("false");
				return null;
			}
		} catch (Exception e) {
			if(tx!=null)	tx = null;
			e.printStackTrace();
			return null;
		}
		
	}

	@Override
	public boolean accountLogout(Account ac) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean update(Account ac) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		try {
			tx = session.beginTransaction();
			System.out.println(ac.getAccountName() + "" + ac.getAccountId());
			session.update(ac);
			tx.commit();
			return true;
			
		} catch (Exception e) {
			// TODO: handle exception
			if(tx!=null)	tx.rollback();
			e.printStackTrace();
			return false;
		}
		finally{
			tx = null;
		}
	}

	@Override
	public Account queryByAccount_id(int account_id) {
		Transaction tx = null;
		Account tempAc = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		 try {
			tx = session.beginTransaction();
			tempAc = (Account)session.get(Account.class, account_id);
			
			tx.commit();
			return tempAc;
			 
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			return tempAc;
		}
		finally{
			 tx = null;
		}
	}

	@Override
	public boolean accountRegister(Account ac) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		 try {
			tx = session.beginTransaction();
			session.save(ac);
			tx.commit();
			return true;
			 
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			return false;
		}
		finally{
			 tx = null;
		}
	}
	
}
